package utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;


public class Agglutina
{
	private String filepath;
	private String outPut;
	private int maxDepth=15;
	private String[] validExtensions={".java",".txt",".csv"};

	public Agglutina(String filepath, String outPut)
	{
		this.filepath=filepath;
		this.outPut=outPut;
	}

	public static void main(String[] args) throws Exception
	{
		String filepath="C:/WorkSpaceDM_Diego/testDM/src/bitmap";
		String outPut="C:/Documents/agglutinato_bitmap.txt";
		Agglutina v= new Agglutina(filepath,outPut);
		v.process();
	}

	private void process() throws IOException
	{
		int depth=9;
		ArrayList<String> fileList = getFileList(depth,filepath);
		System.out.println(fileList.size());
		StringBuffer agg=new StringBuffer();
		for(String file : fileList){
			agg.append(getText(file));
		}	
		
		privateCountWords(agg);
		
		BufferedWriter bw=null; 
		try
		{
			File file = new File(outPut);
			FileWriter fw = new FileWriter(file);
			bw = new BufferedWriter(fw);
			bw.append(agg);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				bw.flush();
				bw.close();
			}
			catch (IOException e)
			{
			}
		}
		System.out.println("done");
	}

	private StringBuffer getText(String file) throws IOException
	{
		StringBuffer f=new StringBuffer(file);
		f.append("\n");
		BufferedReader reader = new BufferedReader(new FileReader(file));	
		String line;
		while ((line = reader.readLine()) != null)
		{
			f.append(line);
			f.append("\n");
		}

		f.append("\n");
		f.append("\n");
		f.append("\n");
		f.append("\n");
		return f;
	}

	
	
	private ArrayList<String> getFileList(int depth, String filepath)
	{
		ArrayList<String> res = new ArrayList<String>();
		if (depth>maxDepth)
			return new ArrayList<String>();
		File mainLevel=new File(filepath);
		for(File file : mainLevel.listFiles()){
			if (!file.isDirectory()){
				if(isVaild(file.getPath())){
					System.out.println(file.getPath());
					if(!res.contains(file.getPath()))
					res.add(file.getPath());
				}
			}
			else{
				res.addAll( getFileList(depth++, file.getPath()));
			}
		}
		
		return res;
	}

	private boolean isVaild(String path)
	{
		for(String s : validExtensions){
			if(path.endsWith(s))
				return true;
		}
		return false;
	}
	
	private void privateCountWords(StringBuffer txtSB){
		
		String txt = txtSB.toString();
		txt.replace("\\n"," ");
		txt.replace("\r"," ");
		txt.replace("\t"," ");
		txt.replace("\\"," ");
		txt.replace(";"," ");
		txt.replace("="," ");
		txt.replace("."," ");
		txt.replace("."," ");
		txt.replace("  "," ");
		String parts[]=txt.split(" ");
		System.out.println(parts.length);
		
	}
}
